<template>
	<view style="display: flex;height: 100vh;flex-direction: column;">
		<js-error mode="bottom" ref="jsError"></js-error>
		<!-- <view style="background-color: #fff;margin-bottom: 10px;">
			<view class="search">
				<u-search @click="show = true" :show-action="false" placeholder="搜索" :disabled="true"></u-search>
			</view>
		</view> -->
		<!-- <view>
			<u-popup v-model="show" mode="right" length="90%">
				<view
					style="font-size: 18px;border-bottom: 1px solid #aaa;font-weight: bold;padding: 10px;display: flex;justify-content: space-between;">
					<text class=" padding-left-sm" style="color: #3E97B0;">筛选</text>
					<text @click="show=false">关闭</text>
				</view>
				<u-form class="form" style="padding: 0 10px;" :model="query" ref="uForm" label-position="left">
				
					<u-form-item class="text-bold" label="公司:" prop="company" label-width="220">
						<js-select v-model="query.companyCode" :showFilter="false" :items="companySelectList"  placeholder="请选择" :tree="true"
							:label-value="query['company.companyName']" @label-input="query['company.companyName'] = $event"></js-select>
					</u-form-item>
					<u-form-item class="text-bold" label="商品编码:" prop="viewCode" label-width="220">
						<u-input placeholder="请输入" v-model="query['basInv.viewCode']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="商品名称:" prop="invName" label-width="220">
						<u-input placeholder="请输入" v-model="query['basInv.invName']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="仓库:" prop="cwhname" label-width="220">
						<u-input placeholder="请输入" v-model="query['basWare.cwhname']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="形象刊:" prop="cfree1" label-width="220">
						<u-input placeholder="请输入" v-model="query['freeVO.cfree1']" type="text" maxlength="200"></u-input>
					</u-form-item>
				</u-form>
				<view class=" flex cu-bar tabbar bg-white foot cu-modal-footer">
					<button class="cu-btn  lines-red lg " @click="reset">重置</button>
					<button class="cu-btn  bg-confirm lg margin-left " @click="submit">查询</button>
				</view>
			</u-popup>
			<u-picker mode="time" v-model="startTime" @confirm="startConfirm"></u-picker>
			<u-picker mode="time" v-model="startTime2" @confirm="startConfirm2"></u-picker>
		</view> -->
		<view style="background-color: #fff;padding: 10px;text-align: center;">
			拣货单：	{{query.pickCode}}
		</view>
		<!-- sum-text="合计" show-summary :summary-method="summaryMethod" -->
		<next-table class="next-table" style="flex: 1;" :show-header="true" :columns="column" :stripe="true" :fit="false" :border="true"  @pageChange="pageChange"
		@toggleRowSelection="toggleRowSelection" @toggleAllSelection="toggleAllSelection"	:data="datalist" :showPaging="true"
		 :pageIndex="query.pageNo" :pageTotal="pageTotal" ></next-table>
		
		
		<view style="height: 60px;"></view>
		<view class="footer" >
			<view style="border-bottom:1px solid #eee ;padding: 10rpx 20rpx 0;display: flex;align-items: center;">
				<view class="">
				<view style="display: flex;align-items: center;" >
					<view style="width: 200rpx;">拣货单总合计：</view>
					<view style="flex: 1;" class=" text-xl"> {{jhQty}}</view>
				</view>
			<!-- 	<view style="display: flex;">
					<view style="width: 220rpx;">剩余/计划重量：</view>
					<view style="flex: 1;"> {{ model.syFhQty|| ""  }}{{ model.planWeight ? '/'+model.planWeight  : ''  }}
						{{ model.basInv&&model.basInv.unitName ? '('+ model.basInv.unitName +')' : '' }}
						
						</view>
				</view> -->
				<view style="display: flex;margin: 10rpx 0;align-items: center;" >
					<view style="width: 200rpx;"> 确认出库合计：</view>
					<view style="flex: 1;" class=" text-xl"> {{ckQty}}</view>
				</view>
				</view>
				<view style="flex: 1;text-align: right;" >
					<button class="cu-btn lines-green shadow-blur" @tap="handleConfirm">
						确认出库
					</button>
				</view>
			</view>
			<!-- <view style=" display: flex;justify-content: space-around;padding: 20rpx ;">
				<button class="cu-btn lines-default shadow-blur" @tap="init()">
					重新装车
				</button>
				<button style="margin: 0 10px;" class="cu-btn lines-green shadow-blur" @tap="submit(vuex_config.FhStatusEnum.OVER)">
					结束装车
				</button>
				<button class="cu-btn bg-green shadow-blur" @tap="submit()">
					<text class="cuIcon-command" style="margin-right: 10rpx;"></text> 保存
				</button>
			</view> -->
		</view>
		
		<!-- <view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="submit" type="primary"
						style="width: 90px; height: 70px; color: #fff; font-size: 20px">确认出库
					</u-button>
				</movable-view>
			</movable-area>
		</view> -->
		<!-- <view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="handleFocus" type="success"
						style="width: 90px; height: 70px; color: #fff; ">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<u-icon style="margin: auto;" name="/static/jeesite/sm1.png" size="80"></u-icon>
							<view>扫一扫</view>
						</view>
					</u-button>
		
				</movable-view>
			</movable-area>
		</view> -->
	
	</view>
</template>
<script>
	import util from '@/common/fire.js'
	export default {
		options: {
			styleIsolation: 'shared'
		},
		data () {
		        return {
					x: 650, //x坐标
					y: 650, //y坐标
					model:{},
					companySelectList:[],
					query: {
						pageNo: 1,
						pageSize: 10,
						status: 0 //查询未确认
					},
					jhQty:0,
					ckQty:0,
					barCode:'',
					focus:false,
					inputStyle:{
					  fontSize:'34rpx',
					  marginRight: '10rpx' ,
					},
					keyword: '',
					show: false,
					startTime: false,
					startTime2: false,
					formDate:'',
					showDate: false,
		            // pageIndex: 1,
		            pageTotal: 0,
					selectList: [],
		            datalist: [],
		            checkNameList: [],
					filters: {},
		            column: [
						{ type:'selection',width:50, fixed: true },
						// fixed:true,
						{ name: 'xuhao', label: '序号', width:50 ,align:'center',},
						{ name: 'djno', label: '出库订单', width:120,},
						{ name: 'fcontacts', label: '联系人' , width:80,},
						{ name: 'fqty', label: '数量', width:70,},
						// 
		            ]
		        }
		    },
			onReady() { },
			onLoad(p) {
				// this.model.companyCode = this.vuex_company.companyCode || '';
				// this.query.companyCode = this.vuex_company.companyCode || '';
				// this.$u.api.ktnw.companyTreeData().then(res => {
				// 	this.companySelectList = res;
				// });
				// if(p.invName){
				// 	this.query['basInv.invName'] = p.invName
				// 	this.query['basInv.viewCode'] = p.viewCode
				// 	this.query['basWare.cwhname'] = p.whname
				// }
				this.query.pickCode =  p.pickCode
				this.getdatalist()
				this.$u.api.ktnw.rdOrderListData({
					...this.query,
					pageSize: 999,
				}).then((res) => {
					res.list.map((item,index)=>{
						this.jhQty += item.fqty
					})
				});
			},
			onHide() {
			},
			onUnload() {
				
			},
			onShow() {
				
			},
		    methods: {
				toggleAllSelection(_, list) {
					this.ckQty = 0
				    // this.checkNameList[this.query.pageNo] = list
				    this.checkNameList = list.map(item=>{
						this.ckQty += item.fqty
						return item
					})
					console.log(this.checkNameList,'this.checkNameList=====');
				},
				toggleRowSelection(bool, list) {
					this.ckQty = 0
				    this.checkNameList = list.map(item=>{
						this.ckQty += item.fqty
						return item
					})
					console.log(this.checkNameList,'this.checkNameList=====');
				},
				handleFocus() {
					var _that = this;
					_that.focus = false;
					setTimeout(() => {
						_that.focus = true;
					}, 500)
				},
				/** 发生声音*/
				sendMp3(name) {
					console.log("=====testClick=====");
					let src = '/static/jeesite/' + name + '.mp3';
					//实例化声音  
					const Audio = uni.createInnerAudioContext();
					Audio.autoplay = true;
					Audio.src = src; //音频地址  
					Audio.play(); //执行播放  
					Audio.onError((res) => {
						console.log(res.errMsg);
						console.log(res.errCode);
					});
					Audio.onPause(function() {
						console.log('end');
						Audio.destroy();
					});
				},
				summaryMethod({columns, data}){
					let sums = [];
					columns.forEach((column, index) => {
					        if (index === 0) {
					            sums[index] = '合计';
					            return;
					        }
					        const values = data.map(item => Number(item[column.name]));
					        const precisions = [];
					        let notNumber = true;
							console.log(values,'values',column.name)
					        values.forEach(value => {
					            if (column.name == 'iqty') {
					                notNumber = false;
					                let decimal = ('' + value).split('.')[1];
					                precisions.push(decimal ? decimal.length : 0);
					            }
					        });
					        const precision = Math.max.apply(null, precisions);
					        if (!notNumber) {
					            sums[index] = values.reduce((prev, curr) => {
					                const value = Number(curr);
					                if (!isNaN(value)) {
					                    return parseFloat((prev + curr).toFixed(Math.min(precision, 20)));
					                } else {
					                    return prev;
					                }
					            }, 0);
					        } else {
					            sums[index] = '';
					        }
					});
					return sums
				},
				invCode(bar, companyCode) {
					let InventoryPrefix = this.vuex_config.InventoryPrefix;
					if (bar.indexOf(InventoryPrefix) != -1) {
						return bar
					} else {
						let code = `inv_${companyCode}_${bar}`
						return code
					}
				},
				BroadcastScanningToObtainData(res) {
					//获取扫描到的条形码
					let barcode = res.code
					
					//判断条形码长度是否大于3
					if(barcode.length > 3){
						//去除换行符
						let newString = barcode.replace('\n;', '');
						
						this.barCode = newString;
						this.confirm()
						//将换行符分割成数组
						// const allItems = newString.split('\n');
						// 	//遍历数组，将每一项添加到arr中
						// 	for(let i = 0;i<allItems.length;i++){
						// 		this.arr.push({
						// 			"content":allItems[i],
						// 			"remarks":this.remarks
						// 		})
						// 	}
					}
				},
				confirm() {
					let _that = this;
					_that.focus = false
					let InventoryPrefix = _that.vuex_config.InventoryPrefix;
					let PositionPrefix = _that.vuex_config.PositionPrefix;
					let InvBarType = _that.vuex_config.InvBarType;
					let PosBarType = _that.vuex_config.PosBarType;
					let bar = encodeURIComponent(this.barCode)
					if (!this.model.companyCode) {
						_that.sendMp3('sb');
						_that.$refs.jsError.showError("", "请先选择公司", "error");
						setTimeout(() => {
							// _that.focus = true;
							_that.barCode = ''
						}, 500)
					} else {
						let barCode = this.invCode(bar, this.model.companyCode)
						this.$u.api.ktnw.getBarInfo({
							barCode: barCode,
							barType: InvBarType,
							companyCode: this.model.companyCode
						}).then((res) => {
							if (res.result == 'true') {
								
								if(res.data.basInv){
									_that.sendMp3('cg');
									setTimeout(() => {
										this.barCode = ''
										_that.focus = true;
									}, 500)
									// this.query.invCode = res.data.basInv?res.data.basInv.invCode:''
									// this.query.invName = res.data.basInv?res.data.basInv.invName:''
									this.query['basInv.viewCode'] = res.data.basInv?res.data.basInv.viewCode:''
									this.query['basInv.invName'] = res.data.basInv?res.data.basInv.invName:''
									
									
									this.$forceUpdate()
									this.query.pageNo = 1;
									this.loadData();
								}else{
									_that.sendMp3('sb');
									let message = '请扫描正确的商品编码'
									_that.$refs.jsError.showError("", message, "error");
								}
									
							} else {
								_that.sendMp3('sb');
								let message = res.message
								_that.$refs.jsError.showError("", message, "error");
								setTimeout(() => {
									this.barCode = ''
									// _that.focus = true;
								}, 500)
							}
							this.barCode = ''
									
						})
					}
				
				},
				search() {
					// var _that = this;
					// _that.focus = false
					// uni.scanCode({
					// 	scanType: ["barCode", "qrCode"],
					// 	// onlyFromCamera: true,
					// 	success: function(res) {
					// 		_that.barCode = res.result;
					// 		_that.confirm()
					// 	},
					// });
				},
				makeSound(name){
					console.log("=====testClick=====");
					let src = '/static/'+name+'.mp3';
					//实例化声音  
					const Audio = uni.createInnerAudioContext();
					Audio.autoplay = true;
					Audio.src = src; //音频地址  
					Audio.play(); //执行播放  
					Audio.onError((res) => {
					});
					Audio.onPause(function() {
						console.log('end');
						Audio.destroy();
					});
				},
				async commonSearch(barCode) {
					let that = this
					//扫存货
					if (util.checkBarcode(barCode, this.vuex_config.InventoryPrefix)
					|| util.checkBarcode(barCode, this.vuex_config.cbatchPrefix)) {
						this.$u.api.mf.getBarInfo({
							barCode,
						}).then(res => {
							if(res.result == 'true'){
								if (!res.error) {
									if(res.data.basInv){
										console.log(res,'res')
										this.query.invCode = res.data.basInv.invCode
										this.query.cbatch =  res.data.batchInfo?res.data.batchInfo.u8Batch:''
										this.$forceUpdate()
										setTimeout(()=>{
											that.makeSound("cg");
										},500)
										that.$u.toast('验证成功！');
									}else{
										setTimeout(()=>{
											that.makeSound("sb");
										},500)
										that.$refs.jsError.showError('', '验证失败！', 'error');
									}
									
								} else {
									setTimeout(()=>{
										that.makeSound("sb");
									},500)
									that.$refs.jsError.showError('', res.error, 'error');
								}
							}else{
								setTimeout(()=>{
									that.makeSound("sb");
								},500)
								that.$refs.jsError.showError('', res.message, 'error');
							}
						})
					} else {
						setTimeout(()=>{
							that.makeSound("sb");
						},500)
						this.$refs.jsError.showError('', '请扫描正确的条码！', 'error');
					}
				
					setTimeout(() => {
						this.barCode = '';
					}, 500);
				
				},
				startConfirm(e) {
					this.query.ddate_gte = e.year + "-" + e.month + "-" + e.day;
				},
				startConfirm2(e) {
					this.query.ddate_lte = e.year + "-" + e.month + "-" + e.day;
				},
				getStateValue(item){
				  this.query.ctype = item;
				},
				handleConfirm(item) {
					const that = this;
					if(!this.checkNameList.length){
						this.$refs.jsError.showError('', '请先选择确认出库的订单！', 'error');
						return false; 
					}
					let arr = this.checkNameList.map(item=>{
						return item.djno 
					})
					console.log(arr.join(','),'===========');
					uni.showModal({
						title: '出库确认',
						content: '是否确认出库？',
						confirmColor: '#00007f',
						success: (res) => {
							if (!res.confirm) {
								return false;
							} else {
								// this.$u.api.ktnw.rdOrderConfirm({
								// 	selIds: arr.join(','),
								// }).then(res => {
								// 	if (res.result == 'true') {
								// 		this.$u.toast(res.message);
								// 		setTimeout(() => {
								// 			uni.navigateBack({
								// 				delta: 1
								// 			})
								// 		}, 500)
								// 	}else{
								// 		this.$refs.jsError.showError('',res.message,'error');
								// 	}
								// });
							}
						}
					})
				},
				submit() {
					this.query.invCode ? this.query.bmustInv = 1 : ''
					this.query.whCode ? this.query.bmustWh = 1 : ''
					setTimeout(() => {
						this.query.pageNo = 1;
						this.loadData();
					}, 100);
				},
				reset() {
					this.query = {
						pageNo: 1,
						pageSize: 10,
					};
					this.loadData();
				},
				dateChange(e) {
					console.log(e);
					this.formDate = e.startDate + ' 至 ' + e.endDate ;
					this.query.ddate_gte = e.startDate
					this.query.ddate_lte  = e.endDate
				},
				loadData(){
					this.show = false;
					this.query.pageNo = 1
					this.getdatalist()
				},
		        getdatalist() {
					
					this.$u.api.ktnw.rdOrderListData(this.query).then((res) => {
						if(!res.list.length){
							this.query.pageNo = 0
						}
						this.datalist = res.list.map((item,index)=>{
							item.xuhao = index+1;
							return item
						})
						this.pageTotal = Math.ceil(res.count /this.query.pageSize); 
					});
					
		        },
		        pageChange(index) {
		            this.query.pageNo = index
		            this.getdatalist()
					this.ckQty = 0
					this.checkNameList = []
		        },
		    },
		    created() {
		        // this.getdatalist()
		    }
	}
</script>
<style lang="scss">
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 70rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透
	
		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件
	
			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
	page {
		// background-color: #f8f8f8;
		background-color:#e6e6e6;
		height: 100vh;
		overflow: hidden;
		
	}
	.cu-bar {
		min-height: 60px;
	}
	
	.cu-btn {
		font-size: 16px;
		height: 40px;
	}
	
	.foot {
		background: #fff;
	}
	.flex-sub{
		margin-left: 10rpx;
	}
	
	.button {
	  font-size: 32rpx;
	  color: #666666;
	  line-height: 40rpx;
	  padding: 12rpx 40rpx;
	  margin-bottom: 20rpx;
	  margin-right: 10rpx;
	  background: #f7f7f7;
	  border-radius: 180rpx;
	}
	.button:hover {
	  background: #3e97b0;
	  color: #ffffff;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}
	.lable-text {
		text-align: justify;
	}
	
	.u-form-item {
		font-size: 28rpx !important;
		padding: 2px !important;
	}
	.footer {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		background: #fff;z-index: 999;
		border-top: 1px solid #eee;
	}
	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;
	
		.cu-btn {
			width: 50%;
		}
	}
	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
	/deep/.table-empty.data-v-3eadd49d {
		// background: #fff;
	    // height: 63vh !important;
		height: 100% !important;;
		border:none !important;;
	}
	
	/deep/.next-table>.data-v-68ab1c7c{
		height:  calc(100% - 50px);
		background: #fff;
		// overflow-y: hidden;
	}
	
	/deep/.next-table-scroll{
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	/deep/.next-table-fixed{
		flex: 1;
		// overflow: scroll;
	}
	/deep/table-empty{
		flex: 1;
	}
	.text-bold {
		font-size: 17px !important;
		padding:10px 0px !important;
	}
	/deep/.u-form-item{
		padding:10px 0px !important;
	}
</style>